package com.sf.bigscreen.qurta;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sf.bigscreen.mapper.ITableConfigMapper;
import com.sf.bigscreen.model.TableConfig;
import com.sf.bigscreen.service.IDayAmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: bi xuan
 * @Date: 2021/9/22 14:42
 * @Description:定时任务，填入全校区域的信息
 **/
@Slf4j
//@Component
public class DayAmAllSchedule implements SchedulingConfigurer {

    @Resource
    private ITableConfigMapper iTableConfigMapper;

    @Autowired
    private IDayAmService iDayAmService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //2.1 从数据库获取执行周期
        TableConfig tableConfig = iTableConfigMapper.selectOne(new LambdaQueryWrapper<TableConfig>().eq(TableConfig::getTableName, "dayam").eq(TableConfig::getInfoStyle, "All"));
        if (tableConfig != null) {
            String cron = tableConfig.getCron();
            taskRegistrar.addTriggerTask(executeSchedule(),
                    triggerContext -> {
                        //2.2 合法性校验.
                        if (StringUtils.isEmpty(cron)) {
                            // Omitted Code ..
                        }
                        //2.3 返回执行周期(Date)
                        return new CronTrigger(cron).nextExecutionTime(triggerContext);
                    });
        }
    }

    private Runnable executeSchedule() {
        return () -> {
            DateTime date = DateUtil.date();
            String dateStr = DateUtil.format(date, "yyyy-MM-dd");
            DateTime yesterday = DateUtil.yesterday();
            String yesterdayStr = DateUtil.format(yesterday, "yyyy-MM-dd");
            iDayAmService.addOrUpdateDayAmAllInfoRangeTime(yesterdayStr, dateStr);
        };
    }
}
